#include <iostream>
#include <vector>
#include<thread>
#include <mutex>
#include <unistd.h>
#include <condition_variable>
using namespace std;

static const int defalute_size = 5;
class Buffer
{
private:
    static void Product(Buffer* Buffer)
    {
        sleep(1);
        vector<int>* buffer = Buffer->_buffer;
        while(true)
        {
            {
                unique_lock <mutex> lck(Buffer->_mutex);
                while(buffer->size() == defalute_size)
                {
                    cout << "生产者沉睡" << endl;
                    Buffer->pro_cond.wait(lck);
                }
                buffer->push_back(1);
                cout << "生产了一条数据" << endl;
                sleep(1);
                if(buffer->size() == defalute_size) 
                {
                    Buffer->com_cond.notify_one();
                }
            }
        }
    }
    static void Com(Buffer* Buffer)
    {
        vector<int>* buffer = Buffer->_buffer;
        while(true)
        {
            {
                unique_lock <mutex> lck(Buffer->_mutex);
                while(buffer->size() == 0)
                {
                    cout << "消费者沉睡" << endl;
                    Buffer->com_cond.wait(lck);
                }
                cout << "消费了一条数据" << endl;
                buffer->pop_back();
                sleep(1);
                if(buffer->size() == 0)
                {
                    Buffer->pro_cond.notify_one();
                }
            }
        }
    }
public:
    Buffer(int size = defalute_size)
    {
        t1 = thread(Product, this);
        t2 = thread(Com, this);
    }
    ~Buffer()
    {
        _buffer = new vector<int>();
        t1.join();
        t2.join();
    }
public:
    vector<int>* _buffer;
    thread t1;
    thread t2;
    condition_variable com_cond;
    condition_variable pro_cond;
    mutex _mutex;
};

int main()
{
    Buffer b;
    return 0;
}